import React, {useEffect, useState,useMemo, memo} from 'react';

import {message} from 'antd';
import IChartsProps from '../ICharts'
import {setConfigs, setData} from '../ChartsConfig'
// @ts-ignore
import createG2 from '../G2Create';
import {tooltip as defaultTooltip} from './DefaultChartConfig'

require('../index.less')

const Line: React.FC<IChartsProps> = memo((props) => {
  const {onSelect, showDataDown, width, height, drillsIcon} = props
  const [records, setRecords] = useState<Array<any>>([]);


  const getValue = (event: any) => {
    let values = []
    values.push(event.data.data)
    setRecords(values)
    return values
  }
  /**
   * 记录点击后的记录值
   * @param event
   * @param chart
   * @param canvas
   */
  const chartClick = (event: any) => {
    let values = getValue(event)
    onSelect && onSelect(values)
  }


  /**
   * 图表渲染
   * @param chart
   * @param configs
   */
  const g2Create = (chart: any, configs: any) => {
    const data: Array<any> = setData(props)
    chart.on('point:click', (ev: any) => {
      ev.data && chartClick(ev)
    });
    if (data && data.length) {
      const types = Array.from(new Set(data.map(v => v.type)))
      if (types && JSON.stringify(types).length > 70) {
        chart.legend(false)
      }
    }

    const {tooltip, position, axis, onEvent} = configs
    chart.tooltip({...tooltip, ...defaultTooltip});
    axis.forEach((val: any) => {
      chart.axis(val.field, val.config);
    })
    chart.line().position(position).color('type')
    chart.point().position(position).color('type').shape('circle');

    onEvent(chart)
    chart.data(data);

    chart.render();
  }
  let G2Create = createG2(g2Create);
  useEffect(() => {
    setRecords([])
    G2Create = createG2(g2Create);

  }, [props])
  /**
   * 下钻
   */
  const dataDown = () => {
    if (records.length == 0) {
      message.info('请选择', 2);

      return
    }
    showDataDown(records)
  }


  const configs = setConfigs(props)
  const G2Chart = useMemo(() => <G2Create
    width={width}
    height={height}
    configs={configs}
  />, [props])
  return (
    <div>
      {showDataDown ?
        <div className='drillBody'>
          {drillsIcon(dataDown)}
        </div> : null}
      {G2Chart}
    </div>
  )

})

export default Line;
